# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.core.validators import EMPTY_VALUES
from django.contrib.localflavor.br.forms import DV_maker


def validate_cnpj(value):
    '''
    Valida um CNPJ
    '''
    messages = {
        'invalid': u'Número de CNPJ inválido.',
        'max_digits': u'Este campo deve conter 14 números.',
        'digits_only': u'Este campo deve conter apenas números.',
        }
    value = value._int

    if value not in EMPTY_VALUES:
        try:
            value = '%0.14i' % int(value)
        except ValueError:
            raise ValidationError(messages['digits_only'])

        if len(value) != 14:
            raise ValidationError(messages['max_digits'])

        orig_dv = value[-2:]

        new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(5, 1, -1) + range(9, 1, -1))])
        new_1dv = DV_maker(new_1dv % 11)
        value = value[:-2] + str(new_1dv) + value[-1]
        new_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(6, 1, -1) + range(9, 1, -1))])
        new_2dv = DV_maker(new_2dv % 11)
        value = value[:-1] + str(new_2dv)
        if value[-2:] != orig_dv:
            raise ValidationError(messages['invalid'])




